<?php
/**
 * Svick a Fast Simple Smart PHP FrameWork
 * Author: Tommy 863758705@qq.com
 * Link: http://svick.tomener.com/
 * Since: 2022
 */

namespace lib\wechat;

use Exception;
use Svick\Http\Client\Http;
use Svick\Log\Log;

class Minapp
{
    /**
     * 获取小程序用户手机号
     *
     * @throws Exception
     */
    public static function getUserPhoneNumber($code): array
    {
        $api_url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . AccessToken::ma();
        $res = Http::post($api_url, ['code' => $code]);
        if ($res->status() != 200) {
            return [1, '网络出错，请稍后重试'];
        }
        $ret = $res->array();

        if ($ret['errcode'] != 0) {
            switch ($ret['errcode']) {
                case -1:
                    $msg = '系统繁忙，请稍后重试';
                    break;
                case 40029:
                    $msg = 'code无效，请重试';
                    break;
                case 45011:
                    $msg = 'API 调用太频繁，请稍候再试';
                    break;
                default:
                    $msg = '获取手机号失败，请稍后重试';
            }
            Log::single(['errcode' => $ret['errcode'], 'msg' => $msg], 'getuserphonenumber.err');
            return [1, $msg];
        }

        $phone = $ret['phone_info']['purePhoneNumber'];

        return [0, $phone];
    }
}
